<?php

namespace app\api\service;

use stdClass;
use think\exception\HttpResponseException;
use think\Response;

/**
 * 接口认证服务
 * Class Base
 * @package app\api\service
 */
class Base
{
    /**
     * 请求参数
     * @var
     */
    public $param;

    /**
     * 当前请求对象
     *
     * @var \think\Request
     */
    protected $request;

    /**
     * 初始化
     * Base constructor.
     */
    public function __construct()
    {
        header('Content-Type:application/json; charset=utf-8');
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:GET,POST,OPTIONS');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');

        $this->request = app('request');
        $this->param = $this->request->param();
    }

    /**
     * 返回自定义请求
     * @param array $data
     */
    protected function response(array $data)
    {
        $result = ['code' => $data['code'], 'msg' => $data['msg'], 'type' => 'json', 'data' => $data['data'] ?? new stdClass()];
        throw new HttpResponseException(Response::create($result, 'json', 200));
    }

    /**
     * 成功请求
     * @param string $msg
     * @param string $data
     * @param int $code
     * @param string $type
     */
    protected function success(string $msg, $data = '', int $code = 1, string $type = 'json')
    {
        $result = ['code' => $code, 'msg' => $msg, 'data' => $data === '' ? new stdClass() : $data, 'type' => $type];
        $this->response($result);
    }

    /**
     * 失败请求
     * @param string $msg
     * @param string $data
     * @param int $code
     * @param string $type
     */
    protected function error(string $msg, $data = '', int $code = 0, string $type = 'json')
    {
        $result = ['code' => $code, 'msg' => $msg, 'data' => $data === '' ? new stdClass() : $data, 'type' => $type];
        $this->response($result);
    }
}